package com.iflytek.uoamp.agent.monitor.timer.monitor;

import com.iflytek.uoamp.agent.common.util.Constant;
import com.iflytek.uoamp.agent.common.util.WFile;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.MonitorItemConfig;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.MonitorPluginType;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentConfig;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentMain;

import org.apache.log4j.Logger;

import java.util.*;

/**
 * Created by noname on 2015/5/11.
 */
public class ComponentInfoListener implements Runnable {

    @Override
    public void run() {
        try {
            List<MonitorItemConfig> cmpInfo = getComponentInfo();
            if (!cmpInfo.isEmpty() && !cmpInfo.get(0).getHeader().isEmpty()) {
                updateComponentInfo(cmpInfo.get(0).getHeader().keySet());
                Logger.getRootLogger().info("component info need update: " + Arrays.toString(cmpset.toArray()));
            } else {
                Logger.getRootLogger().info("component info need no update!!!");
            }
        } catch(Exception e) {
            Logger.getRootLogger().info("component info request throws exception: ", e);
        }
    }


    /***
     * 请求服务端获取组件信息
     * @return
     */
    private List<MonitorItemConfig> getComponentInfo() {
        Object result = MCAgentMain.getSenderClient().sendBySafe(getComponentInfoRequest());
        if (!(result instanceof List)) {
            return new ArrayList<MonitorItemConfig>();
        }
        @SuppressWarnings("unchecked")
        List<MonitorItemConfig> configs = (List<MonitorItemConfig>) result;
        return configs;
    }


    /*****
     * 更新组件列表信息，一部分是内存信息，一部分是文件信息
     * @param cmpInfo
     */
    private void updateComponentInfo(Set<String> cmpInfo) {
        //先更新文件信息
        if (recordCmpFile(cmpInfo)) {
            //更新内存信息
            cmpset = cmpInfo;
        }
    }


    /***
     * 拼接组件信息请求头
     * @return
     */
    private MonitorPluginType getComponentInfoRequest() {
        return new MonitorPluginType(MCAgentConfig.getInstance().getMonitoredPointIp(), Constant.COMPONENTINFOREQTYPE, new ArrayList<String>(cmpset));
    }


    /***
     * 填写组件信息文件
     */
    private boolean recordCmpFile(Set<String> cmpInfo) {
        StringBuilder cmpStr = new StringBuilder();
        String lineSeparator = System.getProperty("line.separator");
        // System.lineSeparator() // jdk1.7
        for (String cmp : cmpInfo) {
            cmpStr.append(cmp + lineSeparator);
        }

        if (!cmpStr.toString().isEmpty()) {
            cmpStr.deleteCharAt(cmpStr.length() - 1);
        }

        return WFile.wf(Constant.COMPONENTRECORDFILE, cmpStr.toString());
    }

    private Set<String> cmpset = new HashSet<String>();
}
